package cn.fufeiii.bt.common.aspect.log;

import cn.fufeiii.bt.common.util.LoggerUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 控制器日志切面
 * 配置{@literal logging.controller.disabled=true}关闭
 *
 * @author FuFei
 */
@Aspect
@Order(10)
@Component
@ConditionalOnProperty(prefix = "logging.controller", name = "enabled", havingValue = "true", matchIfMissing = false)
public class ControllerLogAspect {
    @Autowired
    private ControllerLogProperty controllerLogProperty;

    @Pointcut("within(cn.fufeiii.bt..*..controller..*)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object advice(ProceedingJoinPoint joinPoint) throws Throwable {
        Logger log = null;
        boolean pi = Boolean.TRUE.equals(controllerLogProperty.getPrintIn());
        boolean po = Boolean.TRUE.equals(controllerLogProperty.getPrintIn());
        if (pi || po) {
            log = LoggerUtil.logger(joinPoint);
        }
        String methodName = joinPoint.getSignature().getName();
        if (pi) {
            log.info("函数{}入参:{}", methodName, Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (po) {
                log.info("函数{}出参:{}", methodName, result);
            }
            return result;
        } catch (Exception e) {
            if (pi || po) {
                log.warn("函数{}异常:{}({})", methodName, e.getClass().getSimpleName(), e.getMessage());
            }
            throw e;
        }
    }

}
